package com.achen.controller;

import com.achen.entity.MessageConstant;
import com.achen.entity.Result;
import com.achen.entity.User;
import com.achen.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author achen
 * @create 2020-05-04 1:29
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
    public Result findAll() {
        try {
            List<User> list = userService.findAll();
            return new Result(true, MessageConstant.GET_USER_LIST_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USER_LIST_FAIL);
        }
    }

    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        System.out.println(user);
        try {
            if(StringUtils.isEmpty(user.getId())){
                userService.save(user);
            }else{
                userService.edit(user);
            }
            return new Result(true, MessageConstant.SAVE_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SAVE_USER_FAIL);
        }
    }

    @GetMapping("/del")
    public Result del(String id) {
        System.out.println(id);
        try {
            userService.del(id);
            return new Result(true, MessageConstant.DEL_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DEL_USER_FAIL);
        }

    }

    @GetMapping("/findOne")
    public Result findOne(String id) {
        System.out.println(id);
        try {
            User user = userService.findOne(id);
            return new Result(true, MessageConstant.GET_USER_LIST_SUCCESS, user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USER_LIST_FAIL);
        }
    }

    @GetMapping("/findBySearch")
    public Result findBySearch(String searchName) {
        System.out.println(searchName);
        try {
            List<User> list = userService.findBySearch(searchName);
            System.out.println(list);
            return new Result(true, MessageConstant.GET_USER_LIST_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USER_LIST_FAIL);
        }
    }
}
